package org.jeecg.modules.basic.customer.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.basic.customer.entity.BasicCustomer;
import org.jeecg.modules.basic.customer.mapper.BasicCustomerMapper;
import org.jeecg.modules.basic.customer.service.IBasicCustomerService;
import org.jeecg.modules.basic.supplier.entity.BasicSupplier;
import org.jeecg.modules.basic.supplier.service.IBasicSupplierService;
import org.jeecg.modules.business.doc.outbound.mapper.WmsOutReceiptMapper;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMapper;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 客户信息表
 * @Author: jeecg-boot
 * @Date: 2023-07-21
 * @Version: V1.0
 */
@Service
public class BasicCustomerServiceImpl extends ServiceImpl<BasicCustomerMapper, BasicCustomer> implements IBasicCustomerService {

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    @Autowired
    private WmsInReceiptTaskMapper inReceiptTaskMapper;

    @Autowired
    private WmsOutReceiptMapper outReceiptMapper;

    /**
     * 查询所有客户供应商名称
     *
     * @param name
     * @return
     */
    @Override
    public List<BasicCustomer> listAllCustomerSupplier(String name) {
        List<BasicCustomer> customers = this.list(new LambdaQueryWrapper<BasicCustomer>()
                .like(StringUtils.isNotBlank(name), BasicCustomer::getName, name));
        return customers;
    }

    /**
     * 导入
     *
     * @param request
     */
    @Override
    public Result<String> importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<DictModel> dictList = iSysBaseAPI.getDictItems("custom_type");
                List<String> types = dictList.stream().map(DictModel::getValue).collect(Collectors.toList());
                List<BasicCustomer> list = ExcelImportUtil.importExcel(file.getInputStream(), BasicCustomer.class, params);
                for (BasicCustomer customer : list) {
                    if (StringUtils.isBlank(customer.getName())) {
                        return Result.error("文件导入失败:客商名称不能为空！");
                    }
                    if (StringUtils.isBlank(customer.getType())) {
                        return Result.error("文件导入失败:客商类型不能为空！");
                    }
                    if (!types.contains(customer.getType())) {
                        return Result.error("文件导入失败:客商类型填写错误！");
                    }
                    if (StringUtils.isBlank(customer.getStatus())) {
                        return Result.error("文件导入失败:状态不能为空！");
                    }
                    if (!"0".equals(customer.getStatus()) && !"1".equals(customer.getStatus())) {
                        return Result.error("文件导入失败:状态只能填启用或禁用！");
                    }
                    List<BasicCustomer> names = this.list(new LambdaQueryWrapper<BasicCustomer>()
                            .eq(BasicCustomer::getName, customer.getName()));
                    if (CollectionUtil.isNotEmpty(names)) {
                        return Result.error("文件导入失败:客商名称 " + customer.getName() + " 系统中已存在！");
                    }
                    Object result = FillRuleUtil.executeRule(FillRuleConstant.BASIC_CUSTOMER, new JSONObject());
                    customer.setCode(result.toString());
                }
                this.saveBatch(list);
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    public void updateUsed(String customerId) {
        if (StringUtils.isBlank(customerId)){
            return;
        }

        Integer integer = baseMapper.selectCountById(customerId);
        BasicCustomer basicCustomer = new BasicCustomer();
        basicCustomer.setId(customerId);
        basicCustomer.setUsed(integer);
        baseMapper.updateById(basicCustomer);

    }

    @Override
    public String getIdByCode(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        BasicCustomer customer = this.getOne(new LambdaQueryWrapper<BasicCustomer>().eq(BasicCustomer::getCode, code).eq(BasicCustomer::getKind, 1));
        if (ObjectUtil.isEmpty(customer)) {
            return "";
        }
        return customer.getId();
    }
}
